package pep

import (
	microconfig "github.com/micro/go-config"

	"github.com/micro/go-config/source/consul"
)

type Config struct {
	dbConfig    *dbConfig
	zipkin      *zipkin
	microConfig microconfig.Config
}
type dbConfig struct {
	Hosts   []dbHost
	Driver  string
	Charset string
	Prefix  string
	Change  chan int
}
type dbHost struct {
	Ip       string
	Port     string
	User     string
	Pass     string
	Database string
}
type zipkin struct {
	Url string
}

func newConfig(url, path string) (*Config, error) {
	consulSource := consul.NewSource(
		consul.WithAddress(url),
		consul.StripPrefix(true),
		consul.WithPrefix(path),
	)
	c := &Config{}
	c.microConfig = microconfig.NewConfig()
	c.microConfig.Load(consulSource)
	err := c.newDbConfig()
	if err != nil {
		return nil, err
	}
	err = c.newZipkinConfig()
	if err != nil {
		return nil, err
	}
	go c.watch()
	return c, nil

}
func (c *Config) watch() {
	go func() {
		for {
			c.watchDb()
		}
	}()
}
func (c *Config) watchDb() error {
	w, err := c.microConfig.Watch("database")
	if err != nil {
		return err
	}
	v, err := w.Next()
	if err != nil {
		return err
	}
	var d dbConfig
	err = v.Scan(&d)
	if err != nil {
		return err
	}
	d.Change = c.dbConfig.Change
	c.dbConfig = &d
	c.dbConfig.Change <- 1
	return nil
}
func (c *Config) newDbConfig() error {
	var d dbConfig
	c.microConfig.Get("database").Scan(&d)
	d.Change = make(chan int, 1)
	c.dbConfig = &d
	return nil
}
func (c *Config) newZipkinConfig() error {
	var z zipkin
	c.microConfig.Get("zipkin").Scan(&z)
	c.zipkin = &z
	return nil
}
